package com.hthy.futures.ui.fragment;


import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ListView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hthy.futures.AppConfig;
import com.hthy.futures.R;
import com.hthy.futures.adapter.BillAdapter;
import com.hthy.futures.base.BaseFragment;
import com.hthy.futures.bean.OrderTicket;
import com.hthy.futures.bean.SaveQuotePush;
import com.hthy.futures.bean.ht.BRealTimeData;
import com.hthy.futures.bean.ht.BRealTimeQuotePush;
import com.hthy.futures.inter.BillEvent;
import com.hthy.futures.utils.CacheManager;
import com.hthy.futures.utils.Contant;
import com.hthy.futures.utils.ErrorUtils;
import com.hthy.futures.utils.LogUtils;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.helper.SocketResponsePacket;

import net.hthy.bean.Trade;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import de.greenrobot.event.EventBus;

/**
 * 单据子页面---挂单
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/6
 */

public class BillPendFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {

    private BillAdapter mBillAdapter;

    List<OrderTicket> stopTicket = new ArrayList<>();  // 挂单
    private int mKeyFrg;

    List<OrderTicket> mOrderTickets = new ArrayList<>();

    @Bind(R.id.listView)
    ListView mListView;

    @Bind(R.id.bga)
    BGARefreshLayout mRefreshLayout;


    @Override
    protected int getLayoutId() {
        return R.layout.frg_list;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        // 为BGARefreshLayout 设置代理  (必选）
        mRefreshLayout.setDelegate(this);
        mRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(getActivity(), true));

        Bundle arguments = getArguments();
        mKeyFrg = arguments.getInt(getString(R.string.intent_key_type));

        mBillAdapter = new BillAdapter(getActivity(), mListView, R.layout.adapter_bill_gua, socketClient);
        mBillAdapter.setKeyFlag(mKeyFrg);

    }


    private void loadDataSuccess(List<OrderTicket> mOrderTickets) {
        Collections.reverse(mOrderTickets);
        mRefreshLayout.endRefreshing();
        // 此处需要修改 TODO
        if (mBillAdapter.getDatas().size() > 0) {
            mBillAdapter.clear();
        }

        mBillAdapter.addItem(mOrderTickets);
        mListView.setAdapter(mBillAdapter);
    }

    public void setOrderTickets(List<OrderTicket> orderTickets) {
        if (mOrderTickets.size() > 0) {
            mOrderTickets.clear();
        }
        this.mOrderTickets = orderTickets;

        // 用来过滤是持仓单(需要两个字段来判断）， 还是挂单
        if (stopTicket.size() > 0) {
            stopTicket.clear();
        }

        // 对所有的订单 遍历各个订单，把商品相关的属性赋值进去

        for (OrderTicket orderTicket : mOrderTickets) {

            if ("1".equals(orderTicket.getOrderStatusValue())) {
                stopTicket.add(orderTicket);
            }
        }


        if (1 == mKeyFrg) {
            // 为啥要写在这里才有效啊？啥原因搞不懂
            HashMap<Integer, Boolean> toggleStateMap = new HashMap<Integer, Boolean>();
            for (int i = 0; i < stopTicket.size(); i++) {
                toggleStateMap.put(i, false);
            }
            if (stopTicket.size() > 0) {
                mBillAdapter.setToogleStateMap(toggleStateMap);
            }
            getHistoryData();
            loadDataSuccess(stopTicket);
        }
    }

    @Override
    protected void onResponse(SocketClient client, String responMes, byte[] subBytes) {
        super.onResponse(client, responMes, subBytes);
        LogUtils.e("billfragment" + "是在billfragment" + responMes);

        if (mBillAdapter!=null&& mBillAdapter.isFromBillPOST() && responMes.indexOf("1012") != -1) {
            try {
                Trade.MakeOrderResponseMsg makeOrderResponseMsg = Trade.MakeOrderResponseMsg.parseFrom(subBytes);
                int iErrorCode = makeOrderResponseMsg.getResponseMsg().getIErrorCode();

                int updatePosition = mBillAdapter.getUpdatePosition();
                if (0 == iErrorCode) {
                    // 需要更新这个item
                    if (mBillAdapter.isNeedRemove() == Contant.BILL_OP_CLOSE) {
                        mBillAdapter.removeItem(mBillAdapter.getUpdatePosition());
                        mBillAdapter.notifyDataSetChanged(mListView, updatePosition);
                        showToast(R.string.tip_pancha);
                    } else if (mBillAdapter.isNeedRemove() == Contant.BILL_OP_DELETE) {
                        mBillAdapter.removeItem(mBillAdapter.getUpdatePosition());
                        mBillAdapter.notifyDataSetChanged(mListView, updatePosition);
                        showToast(R.string.tip_delte);
                    } else {
                        // xiu
                        mBillAdapter.notifyDataSetChanged(mListView, updatePosition);
                        showToast("修改成功");
                    }
                } else {
                    ErrorUtils.sendErrorMes(getActivity(), iErrorCode + "");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            mBillAdapter.setFromBillPost(false);
        }
    }

    /**
     * 读历史数据
     */
    private void getHistoryData() {
        SaveQuotePush saveQuotePush = (SaveQuotePush) CacheManager.readObject(getActivity(), AppConfig.OFFETSHEET);
        // 得到报价表的缓存
        if (saveQuotePush != null) {
            List<BRealTimeData> getHistoryOFfersheets = saveQuotePush.mMyRelTimeDatas;
            if (saveQuotePush != null) {
                LogUtils.e("fundcache", "save" + getHistoryOFfersheets.size() + "");
            }
            setNetWorkRealTimeQuotePushes(getHistoryOFfersheets);
        }
    }

    /**
     * 通过缓存数据计算并显示浮动的过程
     */
    private void setNetWorkRealTimeQuotePushes(List<BRealTimeData> getHistoryOFfersheets) {
        for (int i = 0; i <= stopTicket.size() - 1; i++) {
            OrderTicket orderTicket = stopTicket.get(i);
            // 每个单据
            // 遍历行情数据，是要把变化的商品的价格改了
            for (BRealTimeData timpush : getHistoryOFfersheets) {
                String ss_product_code = timpush.product_price_info.ss_product_code;
                // 如果是有浮动的数据item
                if (ss_product_code.equals(orderTicket.getSsProductCode())) {
                    orderTicket.uiPrice = timpush.ui_last_price + "";  // TODO
                    // 这个就不需要刷新adapter
                }
            }
        }
    }

    /**
     * 通过行情计算浮动盈亏 ，与上面还是有点不一样
     *
     * @param bRealTimeQuotePushes
     */
    public void setRealTimeQuotePush(List<BRealTimeQuotePush> bRealTimeQuotePushes) {
        for (int i = 0; i <= stopTicket.size() - 1; i++) {
            OrderTicket orderTicket = stopTicket.get(i);
            // 遍历行情数据，是要把变化的商品的价格改了
            for (BRealTimeQuotePush timpush : bRealTimeQuotePushes) {
                String ss_product_code = timpush.product_price_info.ss_product_code;
                // 如果是有浮动的数据item
                if (ss_product_code.equals(orderTicket.getSsProductCode())) {
                    orderTicket.uiPrice = timpush.ui_price + "";
                    try {
                        // mBillAdapter.setNewPrice(StringUtils.toDouble(orderTicket.uiPrice));
                        //mBillAdapter.setKeyFlag(1);
                        mBillAdapter.notifyDataSetChanged(mListView, i);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout bgaRefreshLayout) {
        EventBus.getDefault().post(new BillEvent(false));
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout bgaRefreshLayout) {
        return false;
    }
}
